package main

import (
	"fmt"
)

type ListNode struct {
	Val  int
	Next *ListNode
}

func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
	var l3 = ListNode{Val: 0}
	a := l1
	b := l2
	flag := 0
	for {
		//找到最后一个节点，稍后优化
		l := &l3
		for {
			if l.Next == nil {
				break
			}
			l = l.Next
		}

		//两个列表都为空了
		if a == nil && b == nil {
			if flag == 1 {
				node := new(ListNode)
				node.Val = flag
				l.Next = node
			}
			break
		}
		//都不为空
		if a != nil && b != nil {
			node := new(ListNode)
			c := a.Val + b.Val + flag
			if c >= 10 {
				flag = 1
				node.Val = c - 10
			} else {
				flag = 0
				node.Val = c
			}
			l.Next = node
			a = a.Next
			b = b.Next
			continue
		}

		//只有a为空
		if a == nil && b != nil {
			node := new(ListNode)
			c := b.Val + flag
			if c >= 10 {
				flag = 1
				node.Val = c - 10
			} else {
				flag = 0
				node.Val = c
			}
			l.Next = node
			b = b.Next
			continue
		}

		//只有b为空
		if a != nil && b == nil {
			node := new(ListNode)
			c := a.Val + flag
			if c >= 10 {
				flag = 1
				node.Val = c - 10
			} else {
				flag = 0
				node.Val = c
			}
			l.Next = node
			a = a.Next
			continue
		}
	}
	return l3.Next
}

func main() {
	l1 := ListNode{Val: 1}
	l2 := ListNode{Val: 2, Next: &l1}
	l3 := ListNode{Val: 5, Next: &l2}
	l7 := ListNode{Val: 7, Next: &l3}
	l4 := ListNode{Val: 4}
	l5 := ListNode{Val: 3, Next: &l4}
	l6 := ListNode{Val: 1, Next: &l5}
	l := addTwoNumbers(&l7, &l6)
	//fmt.Println(l)
	fmt.Println(l.Val, l.Next.Val, l.Next.Next.Val, l.Next.Next.Next.Val)
}
